import axios from 'axios'
import { getCookie } from '@/utils/cookie'
import { ElMessage } from 'element-plus'

export function request (config: any) {
  const instance = axios.create({
    baseURL: 'http://127.0.0.1:8888/api/private/v1/',
    timeout: 5000 // 5s没有请求到数据, 就提示请求失败
  })

  // 请求拦截
  instance.interceptors.request.use(config => {
    const token = getCookie('token')
    if (token) { // 如果有token,在头部加上这个消息
      config.headers.Authorization = token
    }
    return config
  }, err => {
    console.log(err)
  })

  // 响应拦截
  instance.interceptors.response.use(res => {
    return res
  }, err => {
    console.log(err)
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK'){
      ElMessage({type: 'error', message: '网络出错, 请重试', duration: 1500})
    }
    return Promise.reject(err)
  })
  return instance(config)
}
